//
//  EFAMsgVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMsgVC.h"
#import "XDAFNetworking.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFAMsgTCell.h"
#import <RongIMLib/RongIMLib.h>
#import "NSDate+XDTimerFormatter.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import "EFAMsgControlCVC.h"
#import "UIColor+XDHex.h"
#import "MBProgressHUD+XDPrompt.h"
#import <sqlite3.h>
#import "AppDelegate.h"
#import "EFAMsgModel.h"

@interface EFAMsgVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (weak,   nonatomic) IBOutlet UIToolbar *toolbar;
@property (weak,   nonatomic) IBOutlet UIView *selectView;
@property (weak,   nonatomic) IBOutlet UIImageView *selectImgView;
@property (weak,   nonatomic) IBOutlet UILabel *selectLabel;
@property (weak,   nonatomic) IBOutlet UIBarButtonItem *readBarBtnItem;
@property (weak,   nonatomic) IBOutlet UIBarButtonItem *deleteBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *editBarBtnItem;
@property(nonatomic,strong)   UIButton *rightButton;
@property (nonatomic, strong) MJRefreshComponent *refreshViewComponent;
@property(nonatomic,assign)   int pageIndex;
@property(nonatomic,assign)   long countRows;
@property(nonatomic,assign)   long currentTimes;//当前时间
@property(nonatomic,assign)   BOOL isEditMsg;
@property(nonatomic,assign)   BOOL isClickSelectBtn;
@property (assign, nonatomic) BOOL isOenpDB;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

//@property (strong, nonatomic) NSMutableArray<RCConversation *> *conversationList;
@property (strong, nonatomic) NSMutableArray<EFAMsgIMItem *> *msgAllList;
@property (strong, nonatomic) NSMutableArray<EFAMsgIMItem *> *msgList;
@property (strong, nonatomic) NSMutableSet<NSString *> *msgIds;

@end

sqlite3 *database;
static NSString *const kReuseCellId = @"EFAMsgTCell";
//static NSInteger const kRequestUserSize = 20;
int pageSize = 20;

@implementation EFAMsgVC

#pragma mark - life cycle
- (void)dealloc {
    //当对象被回收时关闭通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EFAGlobalNotiGETUIDispatchMsg object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
    _msgIds = [[NSMutableSet alloc]init];
    _msgAllList = [[NSMutableArray alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rcimRefreshHandle:) name:EFAGlobalNotiGETUIDispatchMsg object:nil];
    [self openDB];
    _msgList = [[NSMutableArray alloc]init];
    // 放在这里会导致在其它界面的时候也会一直刷新
     [self selectTable];
    [self tableViewRefresh:nil];
    [self setApplicaitonIconBadge];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rcimRefreshHandle:) name:EFAGlobalNotiGETUIDispatchMsg object:nil];
    NSLog(@"--viewDidAppear--");
}


- (void)viewDidDisappear:(BOOL)animated {
     NSLog(@"--viewDidDisappear--");
    [super viewDidDisappear:animated];
    //在出现页面和消失页面的时候增加通知刷新页面关闭通知
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:EFAGlobalNotiGETUIDispatchMsg object:nil];
}


- (BOOL)hidesBottomBarWhenPushed {
    return self.project_id;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"设备消息";
    self.navigationItem.rightBarButtonItem = self.editBarBtnItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    NSDictionary * normalAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                         NSFontAttributeName: [UIFont systemFontOfSize:15]};
    NSDictionary * disableAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorLightGreen alpha:0.5],
                                         NSFontAttributeName: [UIFont systemFontOfSize:15]};
    
    
    
    [self.readBarBtnItem setTitleTextAttributes:normalAtt forState:UIControlStateNormal];
    [self.deleteBarBtnItem setTitleTextAttributes:normalAtt forState:UIControlStateNormal];
    [self.deleteBarBtnItem setTitleTextAttributes:disableAtt forState:UIControlStateDisabled];
    [self.readBarBtnItem setTitle: @"已读"];
//    [self.deleteBarBtnItem setEnabled:NO];
    [self.toolbar setBarTintColor:[UIColor whiteColor]];
    self.toolbar.hidden = YES;
    
//    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
//    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.backgroundColor = ColorFromRGB(0xeef0f3);
    self.tableView.estimatedRowHeight = 64.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
//    self.tableView.mj_footer = self.mj_footer;
    
    __weak typeof(self) weakSelf = self;
    //..下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
        weakSelf.pageIndex = 1;
        [weakSelf getMessage];
    }];
    
    
    //..上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
        weakSelf.pageIndex = weakSelf.pageIndex + 1;
        [weakSelf getMessage];
    }];
    
    
    UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickSelectView)];
    [_selectView addGestureRecognizer:gr];
    
    
    
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有最近的消息记录" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -50.0;
}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.msgList.count;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.row < self.msgList.count) {
            [self deleteConversationListWithIndexPath:indexPath];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAMsgTCell *cell = [tableView dequeueReusableCellWithIdentifier:[kReuseCellId description]];
    if(!cell){
        cell = [[EFAMsgTCell alloc]init];
        cell.backgroundColor = ColorFromRGB(0xeef0f3);
    }
    [cell isEditingMsg:_isEditMsg];
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    if (indexPath.row < self.msgList.count) {
        [cell configViewWithRCConversation:self.msgList[indexPath.row]];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
// 下面这里会导致无法出现左滑删除，但是不知道是否会影响iOS10上的效果呢？
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(_msgList!= nil && _msgList.count > 0){
        if (_isEditMsg && _msgList != nil) {
            if(_msgList[indexPath.row].isSelected){
                _msgList[indexPath.row].isSelected = NO;
                [_msgIds removeObject:_msgList[indexPath.row].msgId];
            }else{
                _msgList[indexPath.row].isSelected = YES;
                [_msgIds addObject:_msgList[indexPath.row].msgId];
            }
            if(_msgIds.count > 0 && _msgIds.count == _msgList.count){
                _selectImgView.image = [UIImage imageNamed:@"icon_checked"];
            }else{
                _selectImgView.image = [UIImage imageNamed:@"icon_no_checked"];
            }
            _selectLabel.text = [NSString stringWithFormat:@"选择(%ld/%ld)",_msgIds.count,_countRows];
            [self refreshToolBarState];
            return;
        }
        if (indexPath.row < self.msgList.count) {
            EFAMsgIMItem *item = self.msgList[indexPath.row];
            [self jumpToMsgCtrlWithConversation:item];
        }
    
        
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.isEditing) {
        [self refreshToolBarState];
    }
}

#pragma mark - event response
- (void)editBarBtnTapped:(UIButton *)item {
    //点击编辑或者取消之后操作
    _isEditMsg = !_isEditMsg;
    [item setTitle:_isEditMsg ? @"取消" : @"编辑" forState:UIControlStateNormal];
    self.toolbar.hidden = !_isEditMsg;
    UIEdgeInsets edgeInsets = self.tableView.contentInset;
    if (!_isEditMsg) {
        edgeInsets.bottom += CGRectGetHeight(self.toolbar.frame);
        self.tableView.contentInset = edgeInsets;
        self.tableView.scrollIndicatorInsets = edgeInsets;
        [self setMsgListSelected:NO];//所有数据重置为未选中状态
        _countRows = [self getUserAllMsg];//查询当前用户有多少条信息
        if(_msgList.count > _countRows){
            _countRows = _msgList.count;
        }
        _selectLabel.text = [NSString stringWithFormat:@"选择(0/%ld)",_countRows];
        
    } else {
        edgeInsets.bottom -= CGRectGetHeight(self.toolbar.frame);
        self.tableView.contentInset = edgeInsets;
        self.tableView.scrollIndicatorInsets = edgeInsets;
    }
  
    [self refreshToolBarState];
}

-(void)setMsgListSelected:(BOOL)isSelected{
    for(EFAMsgIMItem *item in _msgList){
        if(item.isSelected){
            item.isSelected = isSelected;
        }
    }
            
}

-(void)onClickSelectView{
    _isClickSelectBtn = !_isClickSelectBtn;
    if(_isClickSelectBtn){
        _selectImgView.image = [UIImage imageNamed:@"icon_checked"];
        for(EFAMsgIMItem *item in _msgList){
            if(!item.isSelected){
                item.isSelected = YES;
            }
            [_msgIds addObject:item.msgId];
        }
    }else{
        _selectImgView.image = [UIImage imageNamed:@"icon_no_checked"];
        [_msgIds removeAllObjects];
        [self setMsgListSelected:NO];
      
    }
    _selectLabel.text = [NSString stringWithFormat:@"选择(%ld/%ld)",_msgIds.count,_countRows];
    [self.tableView reloadData];
}

- (IBAction)readBarBtnTapped:(UIBarButtonItem *)sender {
//    NSArray<NSIndexPath *> *array = [self.tableView indexPathsForSelectedRows];
//    if (!array.count) {
//        [self clearAllUnreadMsg];
//        return;
//    }
//    [array enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (obj.row < self.msgList.count) {
//            RCConversation *con = self.msgList[obj.row];
//            [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:con.targetId];
//        }
//    }];
//    [self refreshWholeView];
//    [self editBarBtnTapped:self.rightButton];
    [self updateMessage];
}
- (IBAction)deleteBarBtnTapped:(UIBarButtonItem *)sender {
//    NSArray<NSIndexPath *> *array = [self.tableView indexPathsForSelectedRows];
//    if (!array.count) {
//        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择要删除的消息对象"];
//        return;
//    }
//
//    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:array.count];
//    [array enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (obj.row < self.msgList.count) {
//            RCConversation *con = self.msgList[obj.row];
//            [temp addObject:con];
//            // 输出本地数据库中的会话、记录
//            [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:con.targetId];
//            [[RCIMClient sharedRCIMClient] deleteMessages:ConversationType_PRIVATE targetId:con.targetId success:nil error:nil];
//        }
//    }];
//    [self.msgList removeObjectsInArray:temp];
//    [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationLeft];
//    [self editBarBtnTapped:self.rightButton];
    [self deleteMessage];
}
- (void)rcimRefreshHandle:(NSNotification *)notification {
//    NSLog(@"当前进程: %@", [NSRunLoop currentRunLoop]);
//     NSLog(@"rcimRefreshHandle当前进程: %@",notification.object);
    if(_isEditMsg){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        EFAMsgIMItem *msgItem = notification.object;
          NSLog(@"推送古来的设备id: %@",msgItem.efairydevice_id);
        BOOL isRemove = NO;
        for(EFAMsgIMItem *item in _msgList){
            if([item.msgId isEqualToString:msgItem.msgId]){
                if(item.isSelected){
                    [_msgIds removeObject:item.msgId];
                }
                [_msgList removeObject:item];
                isRemove = YES;
                break;
            }
        }
        [_msgList insertObject:msgItem atIndex:0];
        if(!isRemove){
            _countRows +=1;
             _selectLabel.text = [NSString stringWithFormat:@"选择(0/%ld)",_countRows];
        }
        if(_msgIds.count >0 && _msgIds.count == _msgList.count){
            _selectImgView.image = [UIImage imageNamed:@"icon_checked"];
        }else{
            _selectImgView.image = [UIImage imageNamed:@"icon_no_checked"];
        }
         [self.tableView reloadData];
//        if ([notification.userInfo[@"left"] integerValue] == 0) {
//            [self tableViewRefresh:nil];
//        }
    });
}

#pragma mark - private methods
- (void)refreshToolBarState {
    [self.tableView reloadData];
}
- (void)clearAllUnreadMsg {
//    [self.msgList enumerateObjectsUsingBlock:^(EFAMsgIMItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:obj.targetId];
//    }];
//    [self refreshWholeView];
//    [self editBarBtnTapped:self.editBarBtnItem];
}

- (void)jumpToMsgCtrlWithConversation:(EFAMsgIMItem *)item {
//    NSRange range = [conversation.targetId rangeOfString:@"device_"];
//    if (range.length > 0) {
        UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        EFAMsgControlCVC *vc = [mainSb instantiateViewControllerWithIdentifier:@"EFAMsgControlCVC"];
//        vc.device_id = [[conversation.targetId substringFromIndex:range.length] integerValue];
//        NSLog(@"赋值ID = %ld", (long)vc.device_id);
//        if ([conversation.lastestMessage isMemberOfClass:[RCTextMessage class]]) {
//            RCTextMessage *testMessage = (RCTextMessage *)conversation.lastestMessage;
//            EFAMsgIMItem *item = [EFAMsgIMItem yy_modelWithJSON:testMessage.extra];
            vc.device_name = item.efairydevice_name;
//            NSLog(@"设备id: %@",item.efairydevice_id);
            vc.device_id = [item.efairydevice_id intValue];
//        }
        [self showViewController:vc sender:nil];
    [self updateMessageById:item];
//    }
}
- (void)deleteConversationListWithIndexPath:(NSIndexPath *)indexPath {
    if (!(indexPath.row < self.msgList.count)) {
        return;
    }
//    EFAMsgIMItem *con = self.msgList[indexPath.row];
    [self.msgList removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    // 输出本地数据库中的会话、记录
//    [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:con.targetId];
//    [[RCIMClient sharedRCIMClient] deleteMessages:ConversationType_PRIVATE targetId:con.targetId success:nil error:nil];
}
- (void)refreshWholeView {
//    // 尾部加载更多的显示
//    if (self.userList.totalLoad) {
//        [self.tableView.mj_footer endRefreshingWithNoMoreData];
//    } else {
//        [self.tableView.mj_footer resetNoMoreData];
//    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
//    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestUserListWithHeader:isHeader];
    
//    self.conversationList = [[[RCIMClient sharedRCIMClient] getConversationList:@[@(ConversationType_PRIVATE)]] mutableCopy];
    [self tableViewEndRefresh:isHeader];
    [self refreshWholeView];
}

#pragma mark - network request
#pragma mark - getters and setters
//- (MJRefreshNormalHeader *)mj_header {
//    if (!_mj_header) {
//        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
//        _mj_header.lastUpdatedTimeLabel.hidden = YES;
////        _mj_header.ignoredScrollViewContentInsetTop = 64;
//    }
//    return _mj_header;
//}


- (UIBarButtonItem *)editBarBtnItem {
    if (!_editBarBtnItem) {
        
        
        //开始创建左边按钮
        _rightButton =  [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 52, 30)];
        [_rightButton setTitle:@"编辑" forState:UIControlStateNormal];
        _rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_rightButton setTitleColor:ColorFromRGB(0x282449) forState:UIControlStateNormal];
        [_rightButton setImage:[UIImage imageNamed:@"icon_editor_b"] forState:UIControlStateNormal];
        [_rightButton setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 6.0)];
        [_rightButton addTarget:self action:@selector(editBarBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
        
        _editBarBtnItem = [[UIBarButtonItem alloc]initWithCustomView:_rightButton];
//        _editBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editBarBtnTapped:)];
//        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
//                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
//        [_editBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _editBarBtnItem;
}




-(void) openDB{
    int databaseResult = sqlite3_open([[AppDelegate dbPath] UTF8String], &database);
    if(databaseResult == SQLITE_OK){
        _isOenpDB = YES;
    }
    _isOenpDB = NO;
}

-(void)selectTable{
    //    分页查询
    //   sql语句格式: select 列名 from 表名 where 列名 ＝ 参数       注：前面的列名为查询结果里所需要看到的 列名,后面的 列名 ＝ 参数 用于判断删除哪条数据
    if(!_isOenpDB){
        [self openDB];
    }
//    if(_pageIndex == 1){
//        NSInteger uid = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_id;
        _countRows =  [self getUserAllMsg];
         _currentTimes =  [AppDelegate getNowTimeTimestamp];
//    }
    
    sqlite3_stmt *stmt;
    const char *selectSQL = "select id,efairymsg_from_id,userId,efairydevice_name,efairymsg_add_time,msgAddTime,efairymsg_content,efairymsg_to_id,isRead,efairydevice_id from gtmessage  where msgAddTime >= ?  and userId = ? order by msgAddTime desc limit 0,1000";
    int searchResult = sqlite3_prepare_v2(database, selectSQL, -1, &stmt, nil);
    if (searchResult != SQLITE_OK) {
        NSLog(@"查询失败,%d",searchResult);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"获取数据失败"];
    }
    else{
//        if(_pageIndex > 1){
//            _currentTimes = _msgList[_msgList.count-1].msgAddTime;
//        }else{
        [_msgList removeAllObjects];
        [_msgAllList removeAllObjects];
        [_msgIds removeAllObjects];
        _selectLabel.text = [NSString stringWithFormat:@"选择(%ld/%ld)",_msgIds.count,_countRows];
//        }
        sqlite3_bind_int64(stmt,1,_currentTimes-(6*24*60*60*1000));
        NSInteger userId = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_id;
        sqlite3_bind_text(stmt,2,[[NSString stringWithFormat:@"%ld",userId] UTF8String],-1,NULL);
//        sqlite3_bind_int(stmt,3,_pageIndex);
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            // 查询的结果可能不止一条,直到 sqlite3_step(stmt) != SQLITE_ROW,查询结束。
            EFAMsgIMItem *msgItem= [[EFAMsgIMItem alloc]init];
            msgItem.msgId = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
            msgItem.efairymsg_from_id = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 1)];
            msgItem.userId = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 2)];
            msgItem.efairydevice_name = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 3)];
            msgItem.efairymsg_add_time = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 4)];
            msgItem.msgAddTime = sqlite3_column_int64(stmt, 5);
            msgItem.efairymsg_content = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 6)];
            msgItem.efairymsg_to_id = [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 7)];
            msgItem.isRead = sqlite3_column_int(stmt, 8);
            msgItem.efairydevice_id =  [[NSString alloc] initWithUTF8String:(char*)sqlite3_column_text(stmt, 9)];
            [_msgAllList addObject:msgItem];
        }
    }
     sqlite3_finalize(stmt);
}

-(void) getMessage{
    if(_pageIndex == 1){
        [self selectTable];
    }
    
    int maxNum = _pageIndex * pageSize;
    if(maxNum > _msgAllList.count){
        maxNum = (int)_msgAllList.count;
    }
    int index = (_pageIndex-1) * pageSize;
    for(;index < maxNum ; index++){
        [_msgList addObject:_msgAllList[index]];
    }
    if(_pageIndex == 1){
        [self tableViewEndRefresh:YES];
    }else{
        [self tableViewEndRefresh:NO];
    }
    
    if(_msgList.count >= _msgAllList.count){
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.tableView.mj_footer resetNoMoreData];
    }
    if(_msgIds.count < _msgList.count){
        _selectImgView.image = [UIImage imageNamed: @"icon_no_checked"];
        _isClickSelectBtn = false;
    }else{
        _selectImgView.image = [UIImage imageNamed: @"cion_checked"];
        _isClickSelectBtn = true;
    }
  
    [self refreshWholeView];
}



-(long) getUserAllMsg{
    // 获取未读消息数
    NSString *uid = [NSString stringWithFormat:@"%ld",[EFAModel sharedInstance].loginInfo.user_info.efairyuser_id];
    long  count = 0;
    sqlite3_stmt *stmt;
    const char *selectSQL = "select count(*) from gtmessage where userId = ? and msgAddTime >= ?";
    int updateResult = sqlite3_prepare_v2(database, selectSQL, -1, &stmt, nil);
    if (updateResult != SQLITE_OK) {
//        NSLog(@"获取信息总数失败,%d",updateResult);
    }
    else{
        sqlite3_bind_text(stmt,1,[uid UTF8String],-1,NULL);
        sqlite3_bind_int64(stmt,2,[AppDelegate getNowTimeTimestamp] - (6*24*60*60*1000));
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            count = sqlite3_column_int64(stmt, 0);
        }
        //        count = sqlite3_data_count(stmt);
        //        int count = sqlite3_data_count(stmt);
    }
    sqlite3_finalize(stmt);
    return count;
}

-(void) deleteMessage{
    if(_msgIds.count == 0){
          [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择要删除的消息对象"];
        return;
    }
    sqlite3_stmt *stmt;
    NSString *sDeleteSQL = @"delete from gtmessage where id in (";
    for(NSString *ids in _msgIds){
//        sDeleteSQL = [sDeleteSQL stringByAppendingString:ids,@","];
       sDeleteSQL =  [sDeleteSQL stringByAppendingFormat:@"%@,",ids];
    }
    sDeleteSQL = [sDeleteSQL substringWithRange:NSMakeRange(0, sDeleteSQL.length-1)];
//     NSLog(@"删除数据库语句---->：%@",sDeleteSQL);
    sDeleteSQL = [sDeleteSQL stringByAppendingFormat:@"%@",@")"];
    const char *deleteSQL = [sDeleteSQL UTF8String];
//    NSLog(@"删除数据库语句：%@",sDeleteSQL);
    int result =  sqlite3_prepare_v2(database, deleteSQL, -1, &stmt, NULL);
    if(result == SQLITE_OK){
        sqlite3_step(stmt);
         [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"删除成功"];
        _pageIndex = 1;
        [self getMessage];
    }else{
         [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"删除失败"];
    }
//    int updateResult = sqlite3_prepare_v2(database, deleteSQL, -1, &stmt, nil);
   
    sqlite3_finalize(stmt);
}


-(void)updateMessageById:(EFAMsgIMItem *)item{
    sqlite3_stmt *stmt;
    const char *deleteSQL = "update gtmessage set isRead = ? where id = ?";
    int result =  sqlite3_prepare_v2(database, deleteSQL, -1, &stmt, NULL);
    if(result == SQLITE_OK){
        sqlite3_bind_int(stmt, 1, 1);
        sqlite3_bind_text(stmt, 2, [item.msgId UTF8String], -1, NULL);
        sqlite3_step(stmt);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"修改成功"];
        item.isRead = 1;
        [self.tableView reloadData];
        
    }else{
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"修改失败"];
    }
    sqlite3_finalize(stmt);
}

-(void) updateMessage{
    if(_msgIds.count == 0){
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择消息对象"];
        return;
    }
    sqlite3_stmt *stmt;
    NSString *sUpdateSQL = @"update gtmessage set isRead = ? where id in (";
    for(NSString *ids in _msgIds){
        //        sDeleteSQL = [sDeleteSQL stringByAppendingString:ids,@","];
        sUpdateSQL =  [sUpdateSQL stringByAppendingFormat:@"%@,",ids];
        
    }
    sUpdateSQL = [sUpdateSQL substringWithRange:NSMakeRange(0, sUpdateSQL.length-1)];
//      NSLog(@"修改数据库语句---->：%@",sUpdateSQL);
    sUpdateSQL = [sUpdateSQL stringByAppendingFormat:@"%@",@")"];
    const char *deleteSQL = [sUpdateSQL UTF8String];
//    NSLog(@"修改数据库语句：%@",sUpdateSQL);
    int result =  sqlite3_prepare_v2(database, deleteSQL, -1, &stmt, NULL);
    if(result == SQLITE_OK){
        sqlite3_bind_int(stmt, 1, 1);
        sqlite3_step(stmt);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"修改成功"];
        _pageIndex = 1;
        [self getMessage];
    }else{
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"修改失败"];
    }
    sqlite3_finalize(stmt);
}


-(int) getNotReadMsgNum{
    // 获取未读消息数
    NSInteger uid = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_id;
    int count = 0;
    sqlite3_stmt *stmt;
    const char *selectSQL = "select count(*) from gtmessage where isRead = ? and userId = ? and msgAddTime >= ?";
    int updateResult = sqlite3_prepare_v2(database, selectSQL, -1, &stmt, nil);
    if (updateResult != SQLITE_OK) {
//        NSLog(@"获取信息总数失败,%d",updateResult);
    }
    else{
        sqlite3_bind_int(stmt,1,0);
        sqlite3_bind_text(stmt,2,[[NSString stringWithFormat:@"%ld",uid]UTF8String],-1,NULL);
        sqlite3_bind_int64(stmt,3,[AppDelegate getNowTimeTimestamp]-(6*24*60*60*1000));
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            count = sqlite3_column_int(stmt, 0);
//            NSLog(@"未读信息,%d",count);
        }
        //        count = sqlite3_data_count(stmt);
        //        int count = sqlite3_data_count(stmt);
    }
    sqlite3_finalize(stmt);
    return count;
}

- (void)setApplicaitonIconBadge {
    int unreadMsgCount = [self getNotReadMsgNum];
    if(unreadMsgCount > 1000){
        unreadMsgCount = 1000;
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = unreadMsgCount;
}
@end
